﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Async;

namespace Mefisto4.Core.MEF
{
    [Export(typeof(IDependencyResolver))]
    public class MEFDependencyResolver : IDependencyResolver
    {
        private readonly CompositionContainer _container;

        public MEFDependencyResolver(CompositionContainer container)
        {
            if (container == null)
                throw new ArgumentNullException("container");

            _container = container;

            _container.ComposeExportedValue<CompositionContainer>(_container);
        }

        public object GetService(Type serviceType)
        {
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");

            return _container.GetExportedValues(serviceType).FirstOrDefault();
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");

            return _container.GetExportedValues(serviceType);
        }
    }
}